package com.hyh.validator.web;

import com.hyh.validator.customValidator.entity.Car;
import com.hyh.validator.entity.Person;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Summerday
 */
@RestController
public class ValidateController {

    @PostMapping("/person")
    public Map<String, Object> validatePerson(@Valid @RequestBody Person person) {
        Map<String, Object> map = new HashMap<>();
        //// 如果有参数校验失败，会将错误信息封装成对象组装在BindingResult里
        //if (result.hasErrors()) {
        //    List<String> res = new ArrayList<>();
        //    result.getFieldErrors().forEach(error -> {
        //        String field = error.getField();
        //        Object value = error.getRejectedValue();
        //        String msg = error.getDefaultMessage();
        //        res.add(String.format("错误字段 -> %s 错误值 -> %s 原因 -> %s", field, value, msg));
        //    });
        //    map.put("msg", res);
        //    return map;
        //}
        map.put("msg", "success");
        System.out.println(person);
        return map;
    }


    @PostMapping("/car")
    public Map<String,Object> test(@Valid @RequestBody Car car, BindingResult result) {
        Map<String, Object> body = new HashMap<>();
        if(result.hasErrors()){
            List<String> lists = result.getAllErrors().stream().map(x -> x.getDefaultMessage()).collect(Collectors.toList());
            body.put("msg",lists);
            return body;
        }
        body.put("msg","success");
        return body;
    }
}
